package com.henu.art.controller;

import com.henu.art.entity.AcademicOrigin;
import com.henu.art.service.Imlp.AcademicOriginServiceImpl;
import com.henu.art.service.Imlp.AuthServiceImpl;
import com.henu.art.service.Imlp.CustomRedis;
import com.henu.art.util.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Slf4j
@RequestMapping("academicOrigin")
@Tag(name = "用户管理", description = "用户相关的操作接口")
public class AcademicOriginController {
    @Resource
    private AcademicOriginServiceImpl academicOriginService;
    @Resource
    private CustomRedis customRedis;
    @Resource
    private AuthServiceImpl authService;

    @PutMapping("updateAcademicOrigin")
    public Result<?> update(@RequestBody AcademicOrigin academicOrigin, @RequestHeader("token") String token) {
        try {
            String id = String.valueOf(academicOrigin.getId());
//            String id = authService.getUsernameByToken(token);
//            academicOrigin.setId(Integer.parseInt(id));
            AcademicOrigin existingOrigin = academicOriginService.getById(id);
            if (existingOrigin == null) {
                boolean save = academicOriginService.save(academicOrigin);
                if (save) {
                    return Result.ok("新增成功");
                } else {
                    return Result.error("新增失败");
                }
            } else {
                boolean update = academicOriginService.updateById(academicOrigin);
                if (update) {
                    return Result.ok("修改成功");
                } else {
                    return Result.error("修改失败");
                }
            }
        } catch (Exception e) {
            return Result.error("出现错误" + e.getMessage());
        }
    }

    @GetMapping("getAcademicOriginById")
    public Result<?> getAllAcademicOrigin(@RequestHeader("token") String token, @RequestParam String id) {
        if (id == null) id = authService.getUsernameByToken(token);
        if (id.equals(customRedis.getAdminUsername())) {
            return Result.ok("管理员未设置学缘信息");
        }
        return Result.ok(academicOriginService.getById(id));
    }
}
